using System;
using System.Collections.Generic;
using System.Globalization;
using Granite.Metadata;
using System.Diagnostics.Contracts;

namespace Granite.Data
{
	/// <summary>
	/// Collection of parameters for making a procedure call
	/// </summary>
	public sealed class ProcedureCallParameters : IDictionary<string, object>
	{
		readonly Dictionary<string, object> m_Parameters = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);

		/// <summary>
		/// Gets the number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1" />.
		/// </summary>
		/// <returns>
		/// The number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1" />.
		/// </returns>
		public int Count
		{
			get { return m_Parameters.Count; }
		}

		bool ICollection<KeyValuePair<string, object>>.IsReadOnly
		{
			get { return false; }
		}

		/// <summary>
		/// Adds the named parameter, replacing the original value if it exists
		/// </summary>
		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", MessageId = "0#")]
		public object this[string name]
		{
			get { return m_Parameters[NormalizeKey(name)]; }
			set
			{
				if (name == null)
					throw new ArgumentNullException("name", "name is null or empty.");
				if (String.IsNullOrEmpty(name))
					throw new ArgumentException("name is empty.", "name");
				Contract.EndContractBlock(); 
			

				m_Parameters[NormalizeKey(name)] = NormalizeValue(value);
			}
		}

		/// <summary>
		/// Gets an <see cref="T:System.Collections.Generic.ICollection`1" /> containing the keys of the <see cref="T:System.Collections.Generic.IDictionary`2" />.
		/// </summary>
		/// <returns>
		/// An <see cref="T:System.Collections.Generic.ICollection`1" /> containing the keys of the object that implements <see cref="T:System.Collections.Generic.IDictionary`2" />.
		/// </returns>
		public ICollection<string> Keys
		{
			get { return m_Parameters.Keys; }
		}

		/// <summary>
		/// Gets an <see cref="T:System.Collections.Generic.ICollection`1" /> containing the values in the <see cref="T:System.Collections.Generic.IDictionary`2" />.
		/// </summary>
		/// <returns>
		/// An <see cref="T:System.Collections.Generic.ICollection`1" /> containing the values in the object that implements <see cref="T:System.Collections.Generic.IDictionary`2" />.
		/// </returns>
		public ICollection<object> Values
		{
			get { return m_Parameters.Values; }
		}

		/// <summary>
		/// Add a new paramter value. Will throw and exception if it already exists.
		/// </summary>
		/// <param name="name">Name, which will be normalized. This is not case senstive.</param>
		/// <param name="value">Value, which will be normalized.</param>
		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", MessageId = "0#")]
		public void Add(string name, object value)
		{
			if (name == null)
				throw new ArgumentNullException("name", "name is null or empty.");
			if (String.IsNullOrEmpty(name))
				throw new ArgumentException("name is empty.", "name");
			Contract.EndContractBlock(); 
			
			var item = Normalize(name, value);
			m_Parameters.Add(item.Key, item.Value);
		}

		/// <summary>
		/// Removes all items from the <see cref="T:System.Collections.Generic.ICollection`1" />.
		/// </summary>
		public void Clear()
		{
			m_Parameters.Clear();
		}

		/// <param name="name">Name, which will be normalized. This is not case senstive.</param>
		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", MessageId = "0#")]
		public bool ContainsKey(string name)
		{
			if (name == null)
				throw new ArgumentNullException("name", "name is null or empty.");
			if (String.IsNullOrEmpty(name))
				throw new ArgumentException("name is empty.", "name");
			Contract.EndContractBlock();

			return m_Parameters.ContainsKey(NormalizeKey(name));
		}

		/// <param name="name">Name, which will be normalized. This is not case senstive.</param>
		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", MessageId = "0#")]
		public bool Remove(string name)
		{
			if (name == null)
				throw new ArgumentNullException("name", "name is null or empty.");
			if (String.IsNullOrEmpty(name))
				throw new ArgumentException("name is empty.", "name");
			Contract.EndContractBlock();

			return m_Parameters.Remove(NormalizeKey(name));
		}

		/// <param name="name">Name, which will be normalized. This is not case senstive.</param>
		/// <param name="value">If the function returns false, value is undefined.</param>
		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", MessageId = "0#")]
		public bool TryGetValue(string name, out object value)
		{
			if (name == null)
				throw new ArgumentNullException("name", "name is null or empty.");
			if (String.IsNullOrEmpty(name))
				throw new ArgumentException("name is empty.", "name");
			Contract.EndContractBlock();

			return m_Parameters.TryGetValue(NormalizeKey(name), out value);
		}

		void ICollection<KeyValuePair<string, object>>.Add(KeyValuePair<string, object> item)
		{
			Add(item.Key, item.Value);
		}

		bool ICollection<KeyValuePair<string, object>>.Contains(KeyValuePair<string, object> item)
		{
			var temp = (ICollection<KeyValuePair<string, object>>)m_Parameters;
			return temp.Contains(Normalize(item));
		}

		void ICollection<KeyValuePair<string, object>>.CopyTo(KeyValuePair<string, object>[] array, int arrayIndex)
		{
			var temp = (ICollection<KeyValuePair<string, object>>)m_Parameters;
			temp.CopyTo(array, arrayIndex);
		}

		bool ICollection<KeyValuePair<string, object>>.Remove(KeyValuePair<string, object> item)
		{
			var temp = (ICollection<KeyValuePair<string, object>>)m_Parameters;
			return temp.Remove(Normalize(item));
		}

		IEnumerator<KeyValuePair<string, object>> IEnumerable<KeyValuePair<string, object>>.GetEnumerator()
		{
			var temp = (ICollection<KeyValuePair<string, object>>)m_Parameters;
			return temp.GetEnumerator();
		}

		static KeyValuePair<string, object> Normalize(string name, object value)
		{
			if (name == null)
				throw new ArgumentNullException("name", "name is null or empty.");
			if (String.IsNullOrEmpty(name))
				throw new ArgumentException("name is empty.", "name");
			Contract.EndContractBlock();

			return new KeyValuePair<string, object>(NormalizeKey(name), NormalizeValue(value));
		}

		static KeyValuePair<string, object> Normalize(KeyValuePair<string, object> item)
		{
			if (item.Key == null)
				throw new ArgumentNullException("item", "item.Key is null or empty.");
			if (String.IsNullOrEmpty(item.Key))
				throw new ArgumentException("item.Key is empty.", "item");
			Contract.EndContractBlock(); 
			

			return Normalize(item.Key, item.Value);
		}

		static string NormalizeKey(string name)
		{
			if (name == null)
				throw new ArgumentNullException("name", "name is null or empty.");
			if (String.IsNullOrEmpty(name))
				throw new ArgumentException("name is empty.", "name");
			Contract.EndContractBlock();

			return name.StartsWith("@", StringComparison.Ordinal) ? name.Substring(1) : name;
		}

		static object NormalizeValue(object value)
		{
			return (value == DBNull.Value) ? null : value;
		}

		System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
		{
			var temp = (ICollection<KeyValuePair<string, object>>)m_Parameters;
			return temp.GetEnumerator();
		}

		///// <summary>
		///// Populates the parameter collection using the mapping indicated by CallAttributes placed on properties of interest
		///// </summary>
		///// <param name="actionName">Action anem</param>
		///// <param name="value"></param>
		//public void AutoPopulate(string actionName, object value)
		//{
		//	if (String.IsNullOrEmpty(actionName))
		//		throw new ArgumentException("actionName is null or empty.", "actionName");
		//	if (value == null)
		//		throw new ArgumentNullException("value", "value is null.");
		//	
		//	var metadata = MetadataCache.GetMetadata(value.GetType());
		//	foreach (var property in metadata.Properties)
		//	{
		//		if (property.ActionMap.ContainsKey(actionName))
		//			Add(property.ActionMap[actionName], property.InvokeGet(value));
		//	}
		//}

	}

}
